package org.filetransfer.file_transfer_java_backend.controller;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.filetransfer.file_transfer_java_backend.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
@Slf4j
@RestController
@RequestMapping("/api/files")
public class FileController {
    @Autowired
    private FileUploadService fileUploadService;
    // 文件上传相关API - 不需要认证（匿名上传）
    public record FileUploadInfo(String fileName, long totalSize) {}
    @Operation(summary = "检查文件上传记录是否存在")
    @GetMapping("/upload/{md5}/exists")
    public ResponseEntity<Boolean> checkUploadExists(@PathVariable String md5) {
        return ResponseEntity.ok(fileUploadService.exists(md5));
    }
    @Operation(summary = "获取文件上传记录的所有分片信息")
    @GetMapping("/upload/{md5}/chunks")
    public ResponseEntity<FileUploadService.ChunkInfo[]> getAllChunks(@PathVariable String md5) {
        return ResponseEntity.ok(fileUploadService.getAllChunks(md5));
    }
    @Operation(summary = "新建文件上传记录")
    @PostMapping("/upload/{md5}/start")
    public ResponseEntity<String> newUpload(@PathVariable String md5, @RequestBody FileUploadInfo fileUploadInfo) {
        try {
            fileUploadService.newUpload(md5, fileUploadInfo);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Start upload failed: " + e.getMessage());
        }
    }
    @Operation(summary = "上传文件分片")
    @PostMapping("/upload/{md5}/chunk")
    public ResponseEntity<String> uploadChunk(@PathVariable String md5, @Param("chunkMd5") String chunkMd5, @Param("chunkIndex") int chunkIndex, @Param("chunkOffset") long chunkOffset, @RequestBody byte[] chunkData) {
//        try {
        fileUploadService.commitChunk(md5, chunkMd5, chunkIndex, chunkOffset, chunkData);
        return ResponseEntity.ok().build();
//        } catch (Exception e) {
//            return ResponseEntity.status(500).body("Upload chunk failed: " + e.getMessage());
//        }
    }
    @Operation(summary = "上传文件分片 (Base64)")
    @PostMapping("/upload/{md5}/chunk-base64")
    public ResponseEntity<String> uploadChunkBase64(@PathVariable String md5, @Param("chunkMd5") String chunkMd5, @Param("chunkIndex") int chunkIndex, @Param("chunkOffset") long chunkOffset, @RequestBody String chunkDataBase64) {
//        try {
        // 解码 Base64 数据
        if (chunkDataBase64.startsWith("\"")) {
            chunkDataBase64 = chunkDataBase64.substring(1);
        }
        if (chunkDataBase64.endsWith("\"")) {
            chunkDataBase64 = chunkDataBase64.substring(0, chunkDataBase64.length() - 1);
        }
        byte[] chunkData = Base64.getDecoder().decode(chunkDataBase64);
        fileUploadService.commitChunk(md5, chunkMd5, chunkIndex, chunkOffset, chunkData);
        return ResponseEntity.ok().build();
//        } catch (Exception e) {
//            return ResponseEntity.status(500).body("Upload chunk failed: " + e.getMessage());
//        }
    }
    @Operation(summary = "完成文件上传")
    @PostMapping("/upload/{md5}/complete")
    public String completeUpload(@PathVariable String md5) {
        fileUploadService.complete(md5);
        return md5;
    }
}
